package com.bwie.gateway.filters;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;

import com.bwie.gateway.config.IgnoreWhiteConfig;
import com.bwie.gateway.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class AuthFilter implements GatewayFilter , Ordered {

    @Autowired
    private IgnoreWhiteConfig ignoreWhitesConfig;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取白名单
        List<String> whites = ignoreWhitesConfig.getWhites();

        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();

        //获取当前的请求URI
        String path = request.getURI().getPath();
        //判断
        if(StringUtils.matches(path , whites)){
            //发行
            return chain.filter(exchange);
        }

        //获取token
        String token = request.getHeaders().getFirst(TokenConstants.TOKEN);
        //判断
        if(StringUtils.isBlank(token)){
            return GatewayUtils.errorResponse(exchange , "token不能为空");
        }

        //合法校验
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            return GatewayUtils.errorResponse(exchange , "token不合法");
        }

        //有效性
        String userKey = JwtUtils.getUserKey(token);
        Boolean b = redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        if(!b){
            return GatewayUtils.errorResponse(exchange , "token过期");
        }

        //放行
        return chain.filter(exchange);

    }

    /**
     * 过滤执行顺序
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
